package com.atguigu.demojuc.chap03;

/*//资源类
class ShareDataOne {
    private int data = 0;

    public synchronized void increment() throws InterruptedException {
        //判断
        *//*if (data != 0) {  //导致虚假唤醒
            wait();
        }*//*
        while (data != 0) { //通过while循环判断解决虚假唤醒问题
            wait();
        }

        //干活
        data++;
        System.out.println(Thread.currentThread().getName() + "\t" + "---come in data=" + data);

        //通知
        notifyAll();
    }

    public synchronized void decrement() throws InterruptedException {
        //判断
        *//*if (data != 1) {
            wait();
        }*//*
        while (data != 1) {
            wait();
        }

        //干活
        data--;
        System.out.println(Thread.currentThread().getName() + "\t" + "---come in data=" + data);

        //通知
        notifyAll();
    }
}*/


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

//资源类
class ShareDataOne {
    private int data = 0;
    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void increment() throws InterruptedException {
        lock.lock();
        try {
            //判断
        /*if (data != 0) {  //导致虚假唤醒
            wait();
        }*/
            while (data != 0) { //通过while循环判断解决虚假唤醒问题
                condition.await();
            }

            //干活
            data++;
            System.out.println(Thread.currentThread().getName() + "\t" + "---come in data=" + data);

            //通知
            condition.signal();
            //condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            //判断
        /*if (data != 1) {
            wait();
        }*/
            while (data != 1) {
                condition.await();
            }

            //干活
            data--;
            System.out.println(Thread.currentThread().getName() + "\t" + "---come in data=" + data);

            //通知
            condition.signal();
            // condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}


/**
 * 回顾线程间通信：
 * wait()/notify()/notifyAll() ->  必须在有锁的环境下使用。 配合  synchronized 使用
 * 否则报错：java.lang.IllegalMonitorStateException: current thread is not owner
 * <p>
 * 多线程编程代码模板：(中)
 * 判断
 * 干活
 * 通知
 * <p>
 * 案例： 两个线程操作一个初始值为0的变量，实现一个线程对变量增加1，一个线程对变量减少1，交替10轮。
 * <p>
 * <p>
 * <p>
 * **多线程编程模板（下）：**
 * <p>
 * 防止虚假唤醒（使用while，代替if）
 * while (boolean) {
 * wait();
 * }
 */
public class WaitNotifyDemo {

    public static void main(String[] args) {
        ShareDataOne shareDataOne = new ShareDataOne();

        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    shareDataOne.increment();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "A").start();

        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    shareDataOne.decrement();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "B").start();

        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    shareDataOne.increment();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "C").start();

        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    shareDataOne.decrement();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "D").start();
    }
}
